package com.yunsoft.gateway.interceptor.handler;

import com.alibaba.fastjson.JSON;
import com.fld.platform.commons.entity.auth.Credentials;
import com.fld.platform.commons.entity.auth.CredentialsHolder;
import com.yunsoft.gateway.annotation.WebInterceptor;
import com.yunsoft.gateway.utils.RequestUtils;
import com.yunsoft.gateway.wrapper.RequestWrapper;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

/**
 * 
 * 网关过滤器
 */
@WebInterceptor(name = "gatewayHandlerInterceptor", pathPatterns = { "/**" }, order = 0)
public class GatewayHandlerInterceptor extends BaseHandlerInterceptor {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(GatewayHandlerInterceptor.class);
	
	private static final String COOKHERE_TIME_COUNT = "COOKHERE-TIME-COUNT";

	private static final String REQUEST_IP = "RequestIP";
	

	private Long getAudience(HttpServletRequest request) {
		try {
			checkAuthorization(request);
		} catch(Exception e) {
		}
		Credentials credentials = CredentialsHolder.get();
		if(credentials != null) {
			return credentials.getId();
		}
		return null;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		request.setAttribute(COOKHERE_TIME_COUNT, String.valueOf(System.currentTimeMillis()));
		//
		Long audience = getAudience(request);
		String ip = RequestUtils.getIpAddress(request);
		MDC.put(REQUEST_IP,ip);
		//
		String uri = request.getRequestURI();
		LOGGER.info("[网关][请求][TOKENID={}]:URI={}",(audience == null ? "" : audience), request.getRequestURI());
		LOGGER.info("[网关][请求][TOKENID={}]:IP={}",(audience == null ? "" : audience), ip);

		String contentType = request.getContentType();
		if (ContentType.APPLICATION_JSON.getMimeType().equalsIgnoreCase(contentType) ||
				(
						StringUtils.isNotBlank(contentType) &&
								contentType.toLowerCase().startsWith(ContentType.APPLICATION_JSON.getMimeType().toLowerCase())
				)
		) {
			if (request instanceof RequestWrapper) {
				RequestWrapper requestWrapper = (RequestWrapper) request;
				LOGGER.info("[网关][请求][TOKENID={}]:Params={}",(audience == null ? "" : audience), requestWrapper.getBody());
			}
		} else {
			if(uri.indexOf("/upload/") != -1) {
				Map<String,String[]> parameterMap = RequestUtils.copyParameterMap(request.getParameterMap());
				String value = request.getParameter("base64String");
				if(value != null) {
					int index = value.indexOf(";");
					if(index > 0) {
						String params = value.substring(0,index);
						parameterMap.put("base64String", new String[] {params});
					} else {
						parameterMap.put("base64String", new String[] {"未知图片类型"});
					}
				}
				LOGGER.info("[网关][请求][TOKENID={}]:Params={}",(audience == null ? "" : audience), JSON.toJSONString(parameterMap));
			} else {
				LOGGER.info("[网关][请求][TOKENID={}]:Params={}",(audience == null ? "" : audience), JSON.toJSONString(request.getParameterMap()));
			}
		}

		return true;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		long start = 0;
		try {
			String startValue = (String)request.getAttribute(COOKHERE_TIME_COUNT);
			start = Long.parseLong(startValue);
		} catch(Exception e) {
		}
		//清空
		Credentials credentials = CredentialsHolder.get();
		if(credentials != null) {
			response.setHeader("Authorization", credentials.getJwt());
			response.setHeader("Authorization-Status", credentials.getJwtStatus());
			Cookie userCookie = new Cookie("Authorization", credentials.getJwt()); 
			// cookie的有效期为1个月
//			userCookie.setMaxAge(24 * 60 * 60 * 30);	//不设置时间，仅在会话内有效
			userCookie.setPath("/");
//			userCookie.setDomain(deliveryDomain);
			response.addCookie(userCookie);
			CredentialsHolder.clear();
		}
		Long audience = (credentials == null ? null : credentials.getId());
		//
		Object body = request.getAttribute(ResponseBodyHandler.RESPONSE_BODY);
		if(body != null) {
			LOGGER.info("[网关][返回][TOKENID={}]:{}",(audience == null ? "" : audience),String.valueOf(body));
		} else {
			LOGGER.info("[网关][返回][TOKENID={}]",(audience == null ? "" : audience));
		}
		if(start > 0) {
			LOGGER.info("[网关][返回][TOKENID={}][耗时:{}毫秒]",(audience == null ? "" : audience),System.currentTimeMillis() - start);
		}
		//
		MDC.remove(REQUEST_IP);
		super.afterCompletion(request, response, handler, ex);
	}

}
